#include "InSdkTcpSystemClient.h"
#include "InPerUart.h"
#include "InSdkUpgradeSys.h"

#define DEF_TAG             "InSdkUpgrade"

void Ext_InSdkUpgradeSys_Start(void)
{
    Ext_InSdkTcpSystem_Cmd("check_for_upgrade.sh &");

    /* wait for check version */
    while(DEF_COM_TRUE)
    {
        if(Ext_InComFile_Access(DEF_FLAG_END_OF_CHECK) == DEF_COM_FILE_EXIST)
        {
            PRT_NORMAL("start upgrade now\n");
            break;
        }

        usleep(200 * 1000);
    }

    if(Ext_InComFile_Access(DEF_FLAG_MCU_NEED_UPGRADE) == DEF_COM_FILE_EXIST)
    {
        PRT_NORMAL("mcu upgrade now\n");
    }
    else
    {
        PRT_WARN(DEF_TAG,"mcu don't need upgrade\n");
        goto linux_upgrade;
    }

    Com_s32 start_cnt = 0;
    StComSecondTimer recv_timer;

    Ext_InPerUartSend_Ota_Start();
    sleep(3);
    Ext_InComTimer_GetSec(DEF_COM_SET_NEW_TIME,&recv_timer);

    while(1)
    {
        if(Ext_InPerUart_GetOtaFlag() == DEF_COM_TRUE)
        {
            PRT_NORMAL("mcu return start success\n");
            break;
        }

        if(Ext_InComTimer_GetSec(DEF_COM_NOT_SET_TIME,&recv_timer) >= 25)
        {
            PRT_WARN(DEF_TAG,"mcu return timeout\n");
            goto linux_upgrade;
        }
        else
        {
                start_cnt++;

                if(start_cnt >= 5)
                {
                    Ext_InPerUartSend_Ota_Start();
                    start_cnt = 0;
                }
        }
        sleep(1);
    }

    StComSecondTimer ota_timer;
    Ext_InComTimer_GetSec(DEF_COM_SET_NEW_TIME,&ota_timer);

    /* wait for mcu upgrade complete */
    while(1)
    {
        if(Ext_InComFile_Access(DEF_FLAG_MCU_NEED_UPGRADE) != DEF_COM_FILE_EXIST)
        {
            PRT_NORMAL("mcu upgrade complete\n");
            break;
        }

        /* time out is 2min30s */
        if(Ext_InComTimer_GetSec(DEF_COM_NOT_SET_TIME,&ota_timer) >= 150)
        {
            PRT_WARN(DEF_TAG,"mcu upgrade timeout\n");
            break;
        }

        usleep(200 * 1000);
    }

linux_upgrade :
    if(Ext_InComFile_Access(DEF_FLAG_SOC_NEED_UPGRADE) == DEF_COM_FILE_EXIST)
    {
        PRT_NORMAL("linux upgrade now\n");
        Ext_InSdkTcpSystem_Cmd("upgrade_soc.sh");
        while (Ext_InComFile_Access(DEF_FLAG_SOC_NEED_UPGRADE) == DEF_COM_FILE_EXIST)
        {
            sleep(2);
        }
    }

    PRT_NORMAL("device reboot now\n");
    sleep(2);
    Ext_InSdkTcpSystem_Cmd("reboot");
}
